package com.zkw.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Created by Administrator on 2016/4/30 0030.
 * 服务端
 * 1.socket编程不用nio，要用netty，netty更方便
 * 2.注意ByteBuffer的读写要进行flip()
 */
public class ServerSocketChannelDemo {
    public static void startServer(){
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(8999));
            serverSocketChannel.configureBlocking(false);

            while (true){
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel != null){
                    //接收客户端信息
                    ByteBuffer byteBuffer = ByteBuffer.allocate(48);
                    int size = socketChannel.read(byteBuffer);
                    while (size>0){
                        byteBuffer.flip();
                        Charset charset = Charset.forName("UTF-8");
                        System.out.println(charset.newDecoder().decode(byteBuffer).toString());
                        size = socketChannel.read(byteBuffer);
                    }
                    byteBuffer.clear();

                    //返回信息到客户端
                    ByteBuffer response = ByteBuffer.wrap("hello 小弟！".getBytes("UTF-8"));
                    socketChannel.write(response);
                    response.clear();
                    socketChannel.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        startServer();
    }
}
